﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Com.Maiyoule.GsmSms {
    /// <summary>
    /// GSM控制中心
    /// </summary>
    class GsmContral {
        //分组名称
        private string GroupName;

        //事件回调
        private IEvent callback;

        //串口
        private ComPort cp;

        public GsmContral()
            : this(new Setting(),"default") {
        }

        public GsmContral(Setting setting,string name) {
            this.cp = new ComPort(setting);
            this.cp.DataReceived += new EventHandler(cp_DataReceived);
            this.GroupName = name;

        }
        /// <summary>
        /// 设置回调函数
        /// </summary>
        /// <param name="call"></param>
        public void SetCallBack(IEvent call) {
            this.callback = call;
        }

        /// <summary>
        /// 接收数据处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cp_DataReceived(object sender, EventArgs e) {
            string temp = cp.ReadLine();
            if (temp.Length > 8) {
                if (temp.Substring(0, 6) == "+CMTI:") {
                    //newMsgIndexQueue.Enqueue(Convert.ToInt32(temp.Split(',')[1]));  //存储新信息序号
                    //OnSmsRecieved(e);                                //触发事件
                }
            }
        }
        private virtual void OnRecieved(EventArgs e) {
            if (OnDataRecieved != null) {
                OnDataRecieved(this, e);
            }
        }
        public event EventHandler OnDataRecieved;

        /// <summary>
        /// 开启短信猫
        /// </summary>
        /// <returns>返回结果</returns>
        public bool Open() {
            if (cp.IsOpen()) {
                return true;
            }

            //开启
            if (!cp.Open()) {
                return false;
            }

            if (!cp.IsOpen()) {
                //未成功开启
                return false;
            }

            //成功开启了
            cp.Write("ATEO\r");
            Thread.Sleep(50);
            cp.Write("AT+CMGF=0\r");
            Thread.Sleep(50);
            cp.Write("AT+CNMI=2,1\r");
            return true;
        }

        /// <summary>
        /// 关闭设备
        /// </summary>
        /// <returns></returns>
        public bool Close() {
            if (!cp.IsOpen()) {
                return true;
            }
            return cp.Close();
        }


        /// <summary>
        /// 发送AT指令 逐条发送AT指令 调用一次发送一条指令
        /// 能返回一个OK或ERROR算一条指令
        /// </summary>
        /// <param name="ATCom">AT指令</param>
        /// <returns>发送指令后返回的字符串</returns>
        public string SendAT(string ATCom) {
            string result = string.Empty;
            //忽略接收缓冲区内容，准备发送
            cp.DiscardInBuffer();

            //注销事件关联，为发送做准备
            cp.DataReceived -= cp_DataReceived;

            //发送AT指令
            try {
                cp.Write(ATCom + "\r");
            } catch (Exception ex) {
                cp.DataReceived += cp_DataReceived;
                throw ex;
            }

            //接收数据 循环读取数据 直至收到“OK”或“ERROR”
            try {
                string temp = string.Empty;
                while (temp.Trim() != "OK" && temp.Trim() != "ERROR") {
                    temp = cp.ReadLine();
                    result += temp;
                }
                return result;
            } catch (Exception ex) {
                throw ex;
            } finally {
                //事件重新绑定 正常监视串口数据
                cp.DataReceived += cp_DataReceived;
            }
        }

        /// <summary>
        /// 获取机器码
        /// </summary>
        /// <returns>机器码字符串（设备厂商，本机号码）</returns>
        public string GetMachineNo() {
            string result = this.SendAT("AT+CGMI");
            if (result.Substring(result.Length - 4, 3).Trim() == "OK") {
                result = result.Substring(0, result.Length - 5).Trim();
            } else {
                return null;
            }
            return result;
        }

        /// <summary>
        /// 获取短信中心号码
        /// </summary>
        /// <returns></returns>
        public string GetMessageCenterAddress() {
            string tmp = string.Empty;
            tmp = SendAT("AT+CSCA?");
            if (tmp.Substring(tmp.Length - 4, 3).Trim() == "OK") {
                return tmp.Split('\"')[1].Trim();
            } else {
                return null;
            }
        }

        public void checkOpen() {
            if(!this.cp.IsOpen()){
                this.cp.Open();
            }
        }

        /// <summary>
        /// 获取当前设备时间
        /// </summary>
        /// <returns></returns>
        public DateTime GetModeCurTime() {
            this.checkOpen();
            Thread.Sleep(100);
            try {
                string tmp = SendAT("AT+CCLK?");
                if (tmp.Substring(tmp.Length - 4, 3).Trim() == "OK") {
                    string[] splitarr = tmp.Split('\"');
                    tmp = splitarr[1].Trim();
                    DateTime modetime = DateTime.Parse(tmp);
                    return modetime;
                } else {
                    return DateTime.Parse("00/01/01 00:00:00");
                }
            } catch {
                return DateTime.Parse("00/01/01 00:00:00");
            }

        }

        /// <summary>
        /// 设置猫时间
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public bool SetModeCurTime(DateTime time) {

            checkOpen();
            Thread.Sleep(100);//休眠100毫秒

            string result = SendAT("AT+CCLK=\"" + time.ToString("YY/MM/dd,HH:ii:ss") + "\"");
            if (result.Contains("OK")) {
                return true;
            }
            return false;
        }
    }
}
